// 创建一个调试日志函数，将日志发送到background.js
function debugLog(type, message, data) {
  // 同时保留console.log输出，方便在页面控制台查看
  console.log(`%c${message}`, `color: ${getColorForType(type)}; font-weight: bold`, data);

  // 发送到background.js以便在devtools中查看
  chrome.runtime.sendMessage({
    action: 'contentDebugLog',
    logType: type,
    message: message,
    data: data
  });
}

// 根据日志类型返回不同的颜色
function getColorForType(type) {
  const colors = {
    info: 'blue',
    success: 'green',
    warning: 'orange',
    error: 'red',
    detail: 'purple'
  };
  return colors[type] || 'black';
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  debugLog('info', '收到消息:', request);

  if (request.action === 'fillAddress') {
    // 详细输出地址对象的每个字段，便于调试
    debugLog('detail', '地址数据详情:', {
      收件人: request.address.receiver,
      手机号: request.address.phone,
      省份: request.address.province?.name,
      城市: request.address.city?.name,
      区县: request.address.district?.name,
      街道: request.address.street?.name,
      详细地址: request.address.detailAddress,
      邮政编码: request.address.postcode,
      完整地址对象: request.address
    });

    const result = fillAddressForm(request.address);
    debugLog('success', '填写结果:', result);

    sendResponse({ success: result.success, details: result.details });
    // 向background发送填写结果通知
    chrome.runtime.sendMessage({
      action: 'notifyAddressFilled',
      success: result.success,
      details: result.details
    });
  } else if (request.action === 'detectOrderPage') {
    // 响应订单页面检测请求
    const isOrderPage = detectOrderPage();
    debugLog('info', '是否为订单页面:', isOrderPage);
    sendResponse({ isOrderPage: isOrderPage });
  } else if (request.action === 'readAddress') {
    //  响应读取订单地址
    debugLog('info', '读取地址', 'info');
    // 初始化地址信息
    const result = {
      success: true,
      addressInfo: {
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        street: '',
        address: '',
        zipcode: ''
      },
      errTxt: ''
    };
    const iframes = document.querySelectorAll('iframe');
    if (iframes.length === 0) {
      result.success = false;
      result.errTxt = '未找到地址窗';
      debugLog('info', '未找到地址窗', 'error');
    } else {
      const iframe = iframes[0];
      const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
      result.addressInfo.name = getElementValue(iframeDoc, 'input[id="consignee_name"]');
      result.addressInfo.phone = getElementValue(iframeDoc, 'input[id="consignee_mobile"]');
      const proCityDisStr = getElementValue(iframeDoc, 'div[class="ui-area-text"]');//形如 北京/通州区/宋庄镇 或者 山西/运城市/平陆县/洪池镇
      const proCityDisArr = proCityDisStr.split('/');
      result.addressInfo.province = proCityDisArr[0];
      if (proCityDisArr.length == 3) {
        result.addressInfo.city = "直辖市";
      } else {
        result.addressInfo.city = proCityDisArr[1];
      }
      result.addressInfo.district = proCityDisArr[proCityDisArr.length - 2];
      result.addressInfo.street = proCityDisArr[proCityDisArr.length - 1];
      result.addressInfo.address = getElementValue(iframeDoc, 'input[id="consignee_address"]');
      result.addressInfo.zipcode = getElementValue(iframeDoc, 'input[id="consignee_zip"]');
    }
    debugLog('detail', '读取到的地址信息:', {
      状态: result.success,
      错误文本: result.errTxt,
      收件人: result.addressInfo.name,
      手机号: result.addressInfo.phone,
      省份: result.addressInfo.province,
      城市: result.addressInfo.city,
      区县: result.addressInfo.district,
      街道: result.addressInfo.street,
      详细地址: result.addressInfo.address,
      邮政编码: result.addressInfo.zipcode,
      完整地址对象: result
    });

    sendResponse({ response: result });


  }
  return true; // 保持消息通道开放，允许异步响应
});


function getElementValue(doc, selector) {
  const elements = doc.querySelectorAll(selector);

  if (elements.length == 0) {
    return 'NA';
  }

  debugLog('info', `数量:${elements.length} `, null);
  const element = elements[0];
  if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
    return element.value;
  } else if (element.tagName === 'SELECT') {
    return element.options[element.selectedIndex].value;
  } else if (element.tagName === 'DIV') {
    return element.textContent.trim();
  }
  return '';
}


// 检测当前页面是否为订单页面
function detectOrderPage() {
  // 检查页面是否包含地址表单元素
  const addressElements = document.querySelectorAll(
    'input[name*="address"], input[id*="address"], ' +
    'textarea[name*="address"], textarea[id*="address"], ' +
    'input[placeholder*="地址"], textarea[placeholder*="地址"], ' +
    'input[name*="receiver"], input[name*="consignee"]'
  );

  debugLog('info', '检测订单页面:', null);
  debugLog('info', '找到地址相关元素数量:', addressElements.length);
  if (addressElements.length > 0) {
    debugLog('detail', '找到的地址相关元素:', null);
    addressElements.forEach((el, index) => {
      debugLog('detail', `元素 ${index + 1}:`, {
        tagName: el.tagName,
        id: el.id || '无',
        name: el.name || '无',
        type: el.type || '无',
        placeholder: el.placeholder || '无',
        value: el.value || '无'
      });
    });
  }

  // 检查iframe中是否有地址表单元素
  const iframes = document.querySelectorAll('iframe');
  debugLog('info', `页面中发现 ${iframes.length} 个iframe`, null);

  let iframeHasAddressElements = false;
  iframes.forEach((iframe, index) => {
    try {
      // 尝试访问iframe内容
      const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
      const iframeAddressElements = iframeDoc.querySelectorAll(
        'input[name*="address"], input[id*="address"], ' +
        'textarea[name*="address"], textarea[id*="address"], ' +
        'input[placeholder*="地址"], textarea[placeholder*="地址"], ' +
        'input[name*="receiver"], input[name*="consignee"]'
      );

      debugLog('info', `iframe ${index + 1} 中找到地址相关元素数量:`, iframeAddressElements.length);
      if (iframeAddressElements.length > 0) {
        iframeHasAddressElements = true;
        debugLog('detail', `iframe ${index + 1} 中找到的地址相关元素:`, null);
        iframeAddressElements.forEach((el, elIndex) => {
          debugLog('detail', `元素 ${elIndex + 1}:`, {
            tagName: el.tagName,
            id: el.id || '无',
            name: el.name || '无',
            type: el.type || '无',
            placeholder: el.placeholder || '无',
            value: el.value || '无'
          });
        });
      }
    } catch (error) {
      debugLog('error', `无法访问iframe ${index + 1} 的内容:`, error.message);
    }
  });

  return addressElements.length > 0 || iframeHasAddressElements;
}

// 自动填写地址表单
function fillAddressForm(address) {
  debugLog('info', '开始执行fillAddressForm函数', null);
  debugLog('info', '页面DOM元素数量:', document.querySelectorAll('*').length);

  /*
  // 输出页面中所有的input和select元素，帮助调试
  debugLog('detail', '页面中的输入元素:', null);
  document.querySelectorAll('input, select, textarea').forEach(el => {
    debugLog('detail', `元素: ${el.tagName}, ID: ${el.id || '无'}, Name: ${el.name || '无'}, Type: ${el.type || '无'}, Placeholder: ${el.placeholder || '无'}`, null);
  });*/

  // 记录填写结果
  const results = {
    success: false,
    details: {
      fieldsFound: [],
      fieldsNotFound: [],
      fieldsFilled: []
    }
  };

  // 尝试查找常见的地址表单字段
  const commonSelectors = {
    // 收件人
    receiver: [
      'input[id="consignee_name"]',
      /*
     'input[name="receiver"]',
     'input[name="consignee"]',
     'input[id*="receiver"]',
     'input[id*="consignee"]',
     'input[placeholder*="收件人"]',
     'input[aria-label*="收件人"]',
     'input[name*="name"]',
     'input[id*="name"]',
     'input[placeholder*="姓名"]',
     'input[name*="userName"]',
     'input[id*="userName"]',
     'input[name*="fullName"]',
     'input[id*="fullName"]',
     'input[name*="contactPerson"]',
     'input[id*="contactPerson"]',
     'input[name="consigneeParam.name"]',
     'input[id="chat-textarea"]',
     // 增加更多可能的选择器
     'input[class*="receiver"]',
     'input[class*="consignee"]',
     'input[class*="name"]',
     'input[data-field*="name"]',
     'input[data-field*="receiver"]',
     'input[data-field*="consignee"]',
     'input[data-id*="name"]',
     'input[data-id*="receiver"]',
     'input[data-id*="consignee"]',
     'input[data-name*="name"]',
     'input[data-name*="receiver"]',
     'input[data-name*="consignee"]'
     */
    ],

    // 手机号码
    phone: [
      'input[id="consignee_mobile"]',/*
      'input[name="phone"]',
      'input[name="mobile"]',
      'input[name="tel"]',
      'input[id*="phone"]',
      'input[id*="mobile"]',
      'input[id*="tel"]',
      'input[placeholder*="手机"]',
      'input[placeholder*="电话"]',
      'input[aria-label*="手机"]',
      'input[aria-label*="电话"]',
      'input[name*="cellphone"]',
      'input[id*="cellphone"]',
      'input[name*="contactNumber"]',
      'input[id*="contactNumber"]',
      // 增加更多可能的选择器
      'input[class*="phone"]',
      'input[class*="mobile"]',
      'input[class*="tel"]',
      'input[data-field*="phone"]',
      'input[data-field*="mobile"]',
      'input[data-field*="tel"]',
      'input[data-id*="phone"]',
      'input[data-id*="mobile"]',
      'input[data-id*="tel"]',
      'input[data-name*="phone"]',
      'input[data-name*="mobile"]',
      'input[data-name*="tel"]',
      'input[type="tel"]',
      'input[id="consignee_mobile"]',*/
    ],


    // 下拉框
    xiala: [
      'div[class="ui-area-text"]'
    ],
    // 省份
    province: [
      'div[class*="region"] select:first-child',
      'div[id*="region"] select:first-child',
      'div[class*="area"] select:first-child',
      'div[id*="area"] select:first-child'
    ],

    // 城市
    city: [
      'select[name*="city"]',
      'select[id*="city"]',
      'select[aria-label*="市"]',
      'input[name*="city"]',
      'input[id*="city"]',
      'input[placeholder*="市"]',
      'div[class*="city"] select',
      'div[id*="city"] select',
      // 增加更多可能的选择器
      'select[class*="city"]',
      'select[data-field*="city"]',
      'select[data-id*="city"]',
      'select[data-name*="city"]',
      'div[class*="region"] select:nth-child(2)',
      'div[id*="region"] select:nth-child(2)',
      'div[class*="area"] select:nth-child(2)',
      'div[id*="area"] select:nth-child(2)'
    ],

    // 区/县
    district: [
      'select[name*="district"]',
      'select[name*="county"]',
      'select[id*="district"]',
      'select[id*="county"]',
      'select[aria-label*="区"]',
      'select[aria-label*="县"]',
      'input[name*="district"]',
      'input[name*="county"]',
      'input[id*="district"]',
      'input[id*="county"]',
      'input[placeholder*="区"]',
      'input[placeholder*="县"]',
      'select[name*="area"]',
      'select[id*="area"]',
      'input[name*="area"]',
      'input[id*="area"]',
      'div[class*="district"] select',
      'div[id*="district"] select',
      'div[class*="area"] select',
      'div[id*="area"] select',
      // 增加更多可能的选择器
      'select[class*="district"]',
      'select[class*="county"]',
      'select[class*="area"]',
      'select[data-field*="district"]',
      'select[data-field*="county"]',
      'select[data-field*="area"]',
      'select[data-id*="district"]',
      'select[data-id*="county"]',
      'select[data-id*="area"]',
      'select[data-name*="district"]',
      'select[data-name*="county"]',
      'select[data-name*="area"]',
      'div[class*="region"] select:nth-child(3)',
      'div[id*="region"] select:nth-child(3)',
      'div[class*="area"] select:nth-child(3)',
      'div[id*="area"] select:nth-child(3)'
    ],

    // 详细地址
    detailAddress: [
      'input[id="consignee_address"]',/*
      'input[name*="address"]',
      'input[id*="address"]',
      'textarea[name*="address"]',
      'textarea[id*="address"]',
      'input[placeholder*="详细地址"]',
      'textarea[placeholder*="详细地址"]',
      'input[aria-label*="地址"]',
      'textarea[aria-label*="地址"]',
      'input[placeholder*="街道"]',
      'textarea[placeholder*="街道"]',
      'input[name*="addr"]',
      'input[id*="addr"]',
      'textarea[name*="addr"]',
      'textarea[id*="addr"]',
      'input[name*="detail"]',
      'input[id*="detail"]',
      'textarea[name*="detail"]',
      'textarea[id*="detail"]',
      // 增加更多可能的选择器
      'input[class*="address"]',
      'textarea[class*="address"]',
      'input[class*="addr"]',
      'textarea[class*="addr"]',
      'input[class*="detail"]',
      'textarea[class*="detail"]',
      'input[data-field*="address"]',
      'textarea[data-field*="address"]',
      'input[data-field*="addr"]',
      'textarea[data-field*="addr"]',
      'input[data-field*="detail"]',
      'textarea[data-field*="detail"]',
      'input[data-id*="address"]',
      'textarea[data-id*="address"]',
      'input[data-id*="addr"]',
      'textarea[data-id*="addr"]',
      'input[data-id*="detail"]',
      'textarea[data-id*="detail"]',
      'input[data-name*="address"]',
      'textarea[data-name*="address"]',
      'input[data-name*="addr"]',
      'textarea[data-name*="addr"]',
      'input[data-name*="detail"]',
      'textarea[data-name*="detail"]'*/
    ],

    // 邮政编码
    postcode: [
      'input[name*="postcode"]',
      'input[name*="zipcode"]',
      'input[id*="postcode"]',
      'input[id*="zipcode"]',
      'input[placeholder*="邮编"]',
      'input[placeholder*="邮政编码"]',
      'input[aria-label*="邮编"]',
      'input[aria-label*="邮政编码"]',
      'input[name*="zip"]',
      'input[id*="zip"]',
      'input[name*="postal"]',
      'input[id*="postal"]',
      // 增加更多可能的选择器
      'input[class*="postcode"]',
      'input[class*="zipcode"]',
      'input[class*="zip"]',
      'input[class*="postal"]',
      'input[data-field*="postcode"]',
      'input[data-field*="zipcode"]',
      'input[data-field*="zip"]',
      'input[data-field*="postal"]',
      'input[data-id*="postcode"]',
      'input[data-id*="zipcode"]',
      'input[data-id*="zip"]',
      'input[data-id*="postal"]',
      'input[data-name*="postcode"]',
      'input[data-name*="zipcode"]',
      'input[data-name*="zip"]',
      'input[data-name*="postal"]'
    ]
  };

  console.log('尝试填写收件人字段');
  const receiverResult = fillField(commonSelectors.receiver, address.receiver);
  if (receiverResult) {
    results.details.fieldsFound.push('收件人');
    results.details.fieldsFilled.push('收件人');
  } else {
    results.details.fieldsNotFound.push('收件人');
  }

  debugLog('info', '尝试填写手机号码字段', null);
  const phoneResult = fillField(commonSelectors.phone, address.phone);
  if (phoneResult) {
    results.details.fieldsFound.push('手机号码');
    results.details.fieldsFilled.push('手机号码');
  } else {
    results.details.fieldsNotFound.push('手机号码');
  }

  debugLog('info', '尝试填写详细地址字段', null);
  const detailAddressResult = fillField(commonSelectors.detailAddress, address.detailAddress);
  if (detailAddressResult) {
    results.details.fieldsFound.push('详细地址');
    results.details.fieldsFilled.push('详细地址');
  } else {
    results.details.fieldsNotFound.push('详细地址');
  }

  debugLog('info', "尝试点击下拉框")
  const iframesdxq = document.querySelectorAll('iframe');
  debugLog('info', `找到iframe ${iframesdxq.length}`, null);
  const iframedxq = iframesdxq[0];
  const iframeDoc = iframedxq.contentDocument || iframedxq.contentWindow.document;
  const elements = iframeDoc.querySelectorAll(commonSelectors.xiala);
  debugLog('info', `找到下拉框 ${elements.length}`, null);
  if (elements.length > 0) {
    // elements[0].click();

    const targetElement = elements[0];

    // 创建鼠标悬停事件
    const mouseOverEvent = new MouseEvent('mouseover', {
      bubbles: true,
      cancelable: true,
      view: window
    });

    // 触发事件
    targetElement.dispatchEvent(mouseOverEvent);
    debugLog('info', "已模拟鼠标悬停在标签上", null);
  }

  /*
  // 精准匹配data-id和href属性
const targetLink = iframeDoc.querySelector('a[data-id="1"][href="javascript:void(0)"]');

// 操作元素（如点击）
if (targetLink) {
    targetLink.click(); // 触发点击事件
    console.log("已选中元素:", targetLink.textContent); // 输出文本"北京"
}
    */


  autoFillAddress(iframeDoc, address);

  /*//尝试点击地址

  const xpath = '//a[text()="北京"]';
  debugLog('info', "1级", null);
  const result = iframeDoc.evaluate(xpath, iframeDoc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  const beijingElement = result.singleNodeValue;
  beijingElement.click();

  const xpath2 = '//a[text()="朝阳区"]';
  debugLog('info', "2级", null);
  const result2 = iframeDoc.evaluate(xpath2, iframeDoc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  const beijingElement2 = result2.singleNodeValue;
  beijingElement2.click();

  setTimeout(() => {
    const xpath3 = '//a[text()="八里庄街道"]';
    debugLog('info', "3级", null);
    const result3 = iframeDoc.evaluate(xpath3, iframeDoc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    const beijingElement3 = result3.singleNodeValue;
    beijingElement3.click();
  }, 500);
  */
  /*
  debugLog('info', '尝试填写省份字段', null);
  debugLog('detail', '省份数据:', address.province);
  const provinceResult = fillField(commonSelectors.province, address.province.name);
  if (provinceResult) {
    debugLog('success', '省份字段填写成功', null);
    results.details.fieldsFound.push('省份');
    results.details.fieldsFilled.push('省份');
  } else {
    debugLog('error', '省份字段填写失败', null);
    results.details.fieldsNotFound.push('省份');
  }

  // 延迟填写城市，等待省份选择后的级联效果
  debugLog('warning', '延迟500ms后填写城市...', null);
  setTimeout(() => {
    debugLog('info', '尝试填写城市字段', null);
    debugLog('detail', '城市数据:', address.city);
    const cityResult = fillField(commonSelectors.city, address.city.name);
    if (cityResult) {
      debugLog('success', '城市字段填写成功', null);
      results.details.fieldsFound.push('城市');
      results.details.fieldsFilled.push('城市');
    } else {
      debugLog('error', '城市字段填写失败', null);
      results.details.fieldsNotFound.push('城市');
    }

    // 再次延迟填写区县，等待城市选择后的级联效果
    debugLog('warning', '延迟500ms后填写区县...', null);
    setTimeout(() => {
      debugLog('info', '尝试填写区/县字段', null);
      debugLog('detail', '区县数据:', address.district);
      const districtResult = fillField(commonSelectors.district, address.district.name);
      if (districtResult) {
        debugLog('success', '区县字段填写成功', null);
        results.details.fieldsFound.push('区/县');
        results.details.fieldsFilled.push('区/县');
      } else {
        debugLog('error', '区县字段填写失败', null);
        results.details.fieldsNotFound.push('区/县');
      }
    }, 500);
  }, 500);
  */



  /*
// 尝试填写邮政编码
if (address.postcode) {
  debugLog('info', '尝试填写邮政编码字段', null);
  const postcodeResult = fillField(commonSelectors.postcode, address.postcode);
  if (postcodeResult) {
    results.details.fieldsFound.push('邮政编码');
    results.details.fieldsFilled.push('邮政编码');
  } else {
    results.details.fieldsNotFound.push('邮政编码');
  }
}



// 如果有些网站使用单一地址字段，尝试填写完整地址
debugLog('info', '尝试填写完整地址字段', null);
const fullAddressSelectors = [
  'textarea[name*="full_address"]',
  'textarea[id*="full_address"]',
  'textarea[placeholder*="完整地址"]',
  'input[name*="full_address"]',
  'input[id*="full_address"]',
  'input[placeholder*="完整地址"]'
];

const fullAddressResult = fillField(fullAddressSelectors, address.fullAddress);
if (fullAddressResult) {
  results.details.fieldsFound.push('完整地址');
  results.details.fieldsFilled.push('完整地址');
}

*/

  // 判断填写是否成功
  results.success = results.details.fieldsFilled.length > 0;

  // 显示填写结果通知
  if (results.success) {
    showNotification(`地址信息已自动填写: ${results.details.fieldsFilled.join(', ')}`);
  } else {
    showNotification('地址填写失败，未找到匹配的表单字段');
  }

  debugLog('info', '填写结果:', results);
  return results;
}

function autoFillAddress(iframeDoc, address) {
  debugLog('info', '开始填写地址', address);
  // 1. 构建动态层级配置
  const addressLevels = [
    { text: address.province, delay: 300 },
    { text: address.city, delay: 300 },
    { text: address.district, delay: 300 },
    { text: address.street, delay: 300 },
  ];

  if(address.city === "直辖市"){
    debugLog('info',"直辖市去掉",null)
    addressLevels.splice(1,1);
  }

  const { text: text1, delay: delay1 } = addressLevels[0];
  debugLog('info', `选择省市区 ${text1} ${delay1}`, addressLevels[0]);

  debugLog('info', '修正后的省市区', addressLevels);
  // 2. 递归执行地址选择
  const selectLevel = (level) => {
    if (level >= addressLevels.length) return;

    const { text, delay } = addressLevels[level];
    setTimeout(() => {
      const xpath = `//a[normalize-space(text())="${text}"]`;
      const element = iframeDoc.evaluate(
        xpath,
        iframeDoc,
        null,
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null
      ).singleNodeValue;

      if (element) {
        element.click();
        selectLevel(level + 1); // 触发下一级
      } else {
        debugLog('error', `未找到 "${text}" 选项`, null);
      }
    }, delay);
  };

  // 3. 启动流程
  selectLevel(0);
}

// 调用示例
// autoFillAddress({
//   province: { name: "广东省" },
//   city: { name: "深圳市" },
//   district: { name: "南山区" },
//   street: { name: "粤海街道" }
// });

// 尝试填写表单字段
function fillField(selectors, value) {
  if (!value) {
    debugLog('error', '值为空，跳过填写', null);
    return false;
  }

  debugLog('info', '尝试填写值:', value);
  debugLog('detail', '可用选择器:', selectors);

  // 输出页面中所有可能的表单元素，帮助调试
  debugLog('detail', '页面中的所有表单元素:', null);
  const allFormElements = document.querySelectorAll('input, select, textarea');
  debugLog('info', `总共找到 ${allFormElements.length} 个表单元素`, null);
  /*
  allFormElements.forEach((el, idx) => {
    if (idx < 20) { // 只输出前20个，避免日志过多
      debugLog('detail', `表单元素 ${idx + 1}:`, {
        tagName: el.tagName,
        id: el.id || '无',
        name: el.name || '无',
        type: el.type || '无',
        placeholder: el.placeholder || '无',
        value: el.value || '无',
        visible: isElementVisible(el)
      });
    }
  });*/

  // 检查页面中的iframe
  const iframes = document.querySelectorAll('iframe');
  debugLog('info', `页面中发现 ${iframes.length} 个iframe`, null);

  // 首先尝试在主文档中查找元素
  let mainDocumentSuccess = false;

  /* 不在主文档中尝试
  // 尝试每个可能的选择器
  for (const selector of selectors) {
    debugLog('warning', '尝试选择器:', selector);
    const elements = document.querySelectorAll(selector);
 
    if (elements.length > 0) {
      debugLog('success', `找到匹配字段，选择器: ${selector}，元素数量: ${elements.length}`, null);
 
      // 输出找到的每个元素的详细信息
      Array.from(elements).forEach((element, index) => {
        debugLog('detail', `元素 ${index + 1} 详情:`, {
          标签: element.tagName,
          ID: element.id || '无',
          Name: element.name || '无',
          Type: element.type || '无',
          Value: element.value || '无',
          Placeholder: element.placeholder || '无',
          可见性: isElementVisible(element) ? '可见' : '隐藏',
          禁用状态: element.disabled ? '禁用' : '启用',
          只读状态: element.readOnly ? '只读' : '可写',
          位置: `x=${element.getBoundingClientRect().left}, y=${element.getBoundingClientRect().top}`,
          尺寸: `宽=${element.offsetWidth}, 高=${element.offsetHeight}`,
          计算样式: {
            display: window.getComputedStyle(element).display,
            visibility: window.getComputedStyle(element).visibility,
            opacity: window.getComputedStyle(element).opacity,
            position: window.getComputedStyle(element).position,
            zIndex: window.getComputedStyle(element).zIndex
          }
        });
      });
 
      let fillSuccess = false;
 
      for (const element of elements) {
        debugLog('info', `尝试填写值: ${value}，元素类型: ${element.tagName}`, null);
 
        // 处理ui-area-text类型的下拉组件
        if (element.classList.contains('ui-area-text')) {
          debugLog('info', '检测到ui-area-text下拉组件', {
            id: element.dataset.id,
            title: element.title,
            text: element.textContent
          });
 
          // 尝试查找并设置隐藏的input字段
          const hiddenInput = document.querySelector(`input[name="${element.dataset.id}"]`);
          if (hiddenInput) {
            hiddenInput.value = value;
            triggerInputEvent(hiddenInput);
            debugLog('success', '成功设置ui-area-text组件的隐藏input值', value);
            fillSuccess = true;
            continue;
          }
 
          // 如果没有找到隐藏input，尝试更新显示文本
          element.textContent = value;
          element.title = value;
          triggerChangeEvent(element);
          debugLog('success', '成功设置ui-area-text组件的显示文本', value);
          fillSuccess = true;
          continue;
        }
        // 检查元素是否可见和可编辑
        if (!isElementVisible(element)) {
          debugLog('error', '元素不可见，跳过填写', null);
          continue;
        }
        if (element.disabled) {
          debugLog('error', '元素被禁用，跳过填写', null);
          continue;
        }
        if (element.readOnly) {
          debugLog('error', '元素为只读，跳过填写', null);
          continue;
        }
 
        // 根据元素类型设置值
        let result = false;
        if (element.tagName === 'SELECT') {
          // 对于下拉选择框，查找匹配的选项
          debugLog('info', '检测到SELECT元素，尝试设置选择值', null);
          result = setSelectValue(element, value);
        } else if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
          // 对于输入框和文本区域，使用fillInputField函数
          debugLog('info', `检测到${element.tagName}元素，尝试填充输入值`, null);
          result = fillInputField(element, value);
        }
 
        console.log(`%c填写结果: ${result ? '成功' : '失败'}`, result ? 'color: green; font-weight: bold' : 'color: red; font-weight: bold');
        if (result) fillSuccess = true;
      }
 
      // 如果找到并成功填写了至少一个元素，则返回
      if (fillSuccess) {
        console.log(`%c成功填写字段: ${selector}`, 'color: green; font-weight: bold');
        mainDocumentSuccess = true;
        return true;
      } else {
        console.log(`%c找到字段但填写失败: ${selector}`, 'color: orange; font-weight: bold');
      }
    } else {
      console.log(`%c未找到匹配元素，选择器: ${selector}`, 'color: gray');
    }
  }
    */

  // 如果在主文档中未找到匹配元素，尝试在所有iframe中查找
  if (!mainDocumentSuccess) {
    console.log('%c在主文档中未找到匹配元素，尝试在iframe中查找', 'color: blue; font-weight: bold');

    // 遍历所有iframe
    for (let i = 0; i < iframes.length; i++) {
      try {
        const iframe = iframes[i];
        console.log(`%c检查iframe ${i + 1}:`, 'color: purple', {
          src: iframe.src || '无',
          id: iframe.id || '无',
          name: iframe.name || '无'
        });

        // 尝试访问iframe内容
        const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
        console.log(`%c成功访问iframe ${i + 1} 的内容`, 'color: green');

        // 在iframe中尝试每个选择器
        for (const selector of selectors) {
          console.log(`%c在iframe ${i + 1} 中尝试选择器: ${selector}`, 'color: purple');

          const iframeElements = iframeDoc.querySelectorAll(selector);
          if (iframeElements.length > 0) {
            console.log(`%c在iframe ${i + 1} 中找到匹配字段，选择器: ${selector}，元素数量: ${iframeElements.length}`, 'color: green; font-weight: bold');

            // 输出iframe中找到的元素详情
            Array.from(iframeElements).forEach((element, index) => {
              console.log(`%ciframe中元素 ${index + 1} 详情:`, 'color: blue; font-weight: bold');
              console.log(`  标签: ${element.tagName}`);
              console.log(`  ID: ${element.id || '无'}`);
              console.log(`  Name: ${element.name || '无'}`);
              console.log(`  Type: ${element.type || '无'}`);
              console.log(`  Value: ${element.value || '无'}`);
              console.log(`  Placeholder: ${element.placeholder || '无'}`);
              console.log(`  可见性: ${isElementVisible(element) ? '可见' : '隐藏'}`);
            });

            let iframeSuccess = false;

            for (const iframeElement of iframeElements) {
              console.log(`%c尝试在iframe中填写值: ${value}，元素类型: ${iframeElement.tagName}`, 'color: blue; font-weight: bold');

              // 检查iframe中的元素是否可见和可编辑
              if (!isElementVisible(iframeElement)) {
                console.log('%ciframe中的元素不可见，跳过填写', 'color: red');
                continue;
              }
              if (iframeElement.disabled) {
                console.log('%ciframe中的元素被禁用，跳过填写', 'color: red');
                continue;
              }
              if (iframeElement.readOnly) {
                console.log('%ciframe中的元素为只读，跳过填写', 'color: red');
                continue;
              }

              // 根据元素类型设置值
              let iframeResult = false;
              if (iframeElement.tagName === 'SELECT') {
                console.log('%c检测到iframe中的SELECT元素，尝试设置选择值', 'color: blue');
                iframeResult = setSelectValue(iframeElement, value);
              } else if (iframeElement.tagName === 'INPUT' || iframeElement.tagName === 'TEXTAREA') {
                console.log(`%c检测到iframe中的${iframeElement.tagName}元素，尝试填充输入值`, 'color: blue');
                iframeResult = fillInputField(iframeElement, value);
              }

              console.log(`%ciframe中填写结果: ${iframeResult ? '成功' : '失败'}`, iframeResult ? 'color: green; font-weight: bold' : 'color: red; font-weight: bold');
              if (iframeResult) {
                iframeSuccess = true;
                break;
              }
            }

            if (iframeSuccess) {
              console.log(`%c成功在iframe ${i + 1} 中填写字段: ${selector}`, 'color: green; font-weight: bold');
              return true;
            } else {
              console.log(`%c在iframe ${i + 1} 中找到字段但填写失败: ${selector}`, 'color: orange; font-weight: bold');
            }
          } else {
            console.log(`%c在iframe ${i + 1} 中未找到匹配元素，选择器: ${selector}`, 'color: gray');
          }
        }
      } catch (error) {
        console.log(`%c无法访问iframe ${i + 1} 的内容:`, 'color: red', error.message);
      }
    }
  }

  // 如果所有选择器都未找到匹配字段，尝试使用更通用的方法查找
  console.log('%c尝试使用更通用的方法查找字段', 'color: blue; font-weight: bold');

  // 1. 尝试查找包含相关文本的标签附近的输入元素
  const labelTexts = {
    receiver: ['收件人', '姓名', '联系人'],
    phone: ['手机', '电话', '联系方式', '联系电话', '手机号码'],
    province: ['省', '省份'],
    city: ['市', '城市'],
    district: ['区', '县', '区县'],
    detailAddress: ['详细地址', '街道', '地址', '详细'],
    postcode: ['邮编', '邮政编码', '邮政']
  };

  // 根据value值判断当前填写的是哪种类型的字段
  let fieldType = null;
  for (const type in labelTexts) {
    if (type === 'receiver' && typeof value === 'string') {
      fieldType = type;
      break;
    } else if (type === 'phone' && /^\d{11}$/.test(value)) {
      fieldType = type;
      break;
    } else if (type === 'province' && value.includes('省') || value.includes('市')) {
      fieldType = type;
      break;
    } else if (type === 'city' && value.includes('市')) {
      fieldType = type;
      break;
    } else if (type === 'district' && (value.includes('区') || value.includes('县'))) {
      fieldType = type;
      break;
    } else if (type === 'detailAddress' && value.length > 5) {
      fieldType = type;
      break;
    } else if (type === 'postcode' && /^\d{6}$/.test(value)) {
      fieldType = type;
      break;
    }
  }

  if (fieldType) {
    console.log(`%c识别当前字段类型为: ${fieldType}`, 'color: purple; font-weight: bold');
    const relevantLabels = labelTexts[fieldType];

    // 查找包含相关文本的标签
    for (const labelText of relevantLabels) {
      console.log(`%c尝试查找包含文本「${labelText}」的标签`, 'color: orange');

      // 使用XPath查找包含特定文本的标签或文本节点
      const xpathResult = document.evaluate(
        `//*[contains(text(), '${labelText}')] | //label[contains(., '${labelText}')]`,
        document,
        null,
        XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
        null
      );

      console.log(`%c找到 ${xpathResult.snapshotLength} 个相关标签`, 'color: blue');

      // 遍历找到的每个标签
      for (let i = 0; i < xpathResult.snapshotLength; i++) {
        const labelElement = xpathResult.snapshotItem(i);
        console.log(`%c找到标签:`, 'color: green', labelElement);

        // 尝试方法1: 检查标签是否有for属性
        if (labelElement.tagName === 'LABEL' && labelElement.htmlFor) {
          const inputElement = document.getElementById(labelElement.htmlFor);
          if (inputElement && (inputElement.tagName === 'INPUT' || inputElement.tagName === 'SELECT' || inputElement.tagName === 'TEXTAREA')) {
            console.log('%c通过for属性找到关联输入元素', 'color: green; font-weight: bold');

            // 尝试填写该元素
            let result = false;
            if (inputElement.tagName === 'SELECT') {
              result = setSelectValue(inputElement, value);
            } else {
              result = fillInputField(inputElement, value);
            }

            if (result) {
              console.log('%c成功填写通过标签找到的字段', 'color: green; font-weight: bold');
              return true;
            }
          }
        }

        // 尝试方法2: 查找标签附近的输入元素
        // 首先检查标签的下一个兄弟元素
        let nextElement = labelElement.nextElementSibling;
        if (nextElement && (nextElement.tagName === 'INPUT' || nextElement.tagName === 'SELECT' || nextElement.tagName === 'TEXTAREA')) {
          console.log('%c找到标签的下一个兄弟输入元素', 'color: green');

          // 尝试填写该元素
          let result = false;
          if (nextElement.tagName === 'SELECT') {
            result = setSelectValue(nextElement, value);
          } else {
            result = fillInputField(nextElement, value);
          }

          if (result) {
            console.log('%c成功填写标签兄弟元素', 'color: green; font-weight: bold');
            return true;
          }
        }

        // 尝试方法3: 查找标签的父元素下的输入元素
        const parentElement = labelElement.parentElement;
        if (parentElement) {
          const inputElements = parentElement.querySelectorAll('input, select, textarea');
          console.log(`%c在父元素下找到 ${inputElements.length} 个输入元素`, 'color: blue');

          for (const inputElement of inputElements) {
            if (inputElement !== labelElement) { // 确保不是标签本身
              console.log('%c尝试填写父元素下的输入元素', 'color: orange');

              // 尝试填写该元素
              let result = false;
              if (inputElement.tagName === 'SELECT') {
                result = setSelectValue(inputElement, value);
              } else {
                result = fillInputField(inputElement, value);
              }

              if (result) {
                console.log('%c成功填写父元素下的输入元素', 'color: green; font-weight: bold');
                return true;
              }
            }
          }
        }
      }
    }
  }

  console.log('%c所有方法均未找到匹配的字段', 'color: red; font-weight: bold');
  return false;
}

// 填充输入字段
function fillInputField(field, value) {
  try {
    console.log('%c开始填充输入字段', 'color: blue; font-weight: bold');
    console.log('%c字段信息:', 'color: purple', {
      tagName: field.tagName,
      id: field.id || '无',
      name: field.name || '无',
      type: field.type || '无',
      placeholder: field.placeholder || '无',
      originalValue: field.value || '无',
      newValue: value
    });

    // 检查元素是否可见
    const isVisible = isElementVisible(field);
    if (!isVisible) {
      console.log('%c元素不可见，可能无法正确填写', 'color: orange; font-weight: bold');
    }

    const originalValue = field.value;

    // 尝试方法1: 直接设置value属性
    console.log('%c尝试方法1: 直接设置value属性', 'color: orange');
    field.value = value;

    // 检查值是否成功设置
    if (field.value === value) {
      console.log(`%c方法1成功: 成功设置字段值: ${value}`, 'color: green; font-weight: bold');
      triggerInputEvent(field);
      return true;
    } else {
      console.log(`%c方法1失败: 设置字段值失败，当前值: ${field.value}，期望值: ${value}`, 'color: red');

      // 尝试方法2: 使用execCommand
      if (field.type === 'text' || field.type === 'tel' || field.type === 'textarea' || !field.type) {
        console.log('%c尝试方法2: 使用execCommand', 'color: orange');
        // 尝试使用模拟输入事件
        field.focus();
        field.select();
        const execResult = document.execCommand('insertText', false, value);
        console.log(`%c方法2结果: ${execResult ? '成功' : '失败'}, 当前值: ${field.value}`, execResult ? 'color: green' : 'color: red');
        triggerInputEvent(field);

        if (field.value === value) {
          console.log(`%c方法2最终成功: 成功设置字段值: ${value}`, 'color: green; font-weight: bold');
          return true;
        }
      }

      // 尝试方法3: 使用setAttribute
      console.log('%c尝试方法3: 使用setAttribute', 'color: orange');
      field.setAttribute('value', value);
      console.log(`%c方法3结果: 当前值: ${field.value}`, field.value === value ? 'color: green' : 'color: red');
      triggerInputEvent(field);

      if (field.value === value) {
        console.log(`%c方法3最终成功: 成功设置字段值: ${value}`, 'color: green; font-weight: bold');
        return true;
      }

      console.log('%c所有方法均失败，无法设置字段值', 'color: red; font-weight: bold');
      return false;
    }
  } catch (error) {
    console.error(`%c填充字段时出错: ${error.message}`, 'color: red; font-weight: bold');
    console.error(error);
    return false;
  }
}

// 检查元素是否可见
function isElementVisible(element) {
  try {
    // 获取元素的计算样式
    let style;
    let isInIframe = false;

    try {
      // 检查元素是否在iframe中
      isInIframe = element.ownerDocument !== document;

      if (isInIframe) {
        // 如果是iframe中的元素，使用iframe的contentWindow
        const ownerDocument = element.ownerDocument;
        const defaultView = ownerDocument.defaultView || ownerDocument.parentWindow;
        if (defaultView) {
          style = defaultView.getComputedStyle(element);
        } else {
          // 如果无法获取defaultView，使用主文档的getComputedStyle
          style = window.getComputedStyle(element);
        }
      } else {
        // 主文档中的元素
        style = window.getComputedStyle(element);
      }
    } catch (e) {
      console.log(`%c获取元素样式时出错: ${e.message}`, 'color: orange');
      // 如果出错，尝试使用主文档的getComputedStyle
      style = window.getComputedStyle(element);
    }

    // 检查各种可见性条件
    // 对于iframe中的元素，offsetParent可能为null，但元素仍然可见
    // 因此我们放宽这个条件，只检查其他可见性属性
    let hasValidOffsetParent = true;
    if (!isInIframe) {
      // 只在主文档中检查offsetParent
      hasValidOffsetParent = element.offsetParent !== null;
    }

    const isVisible = (
      hasValidOffsetParent &&
      style.display !== 'none' && // 元素不是display:none
      style.visibility !== 'hidden' && // 元素不是visibility:hidden
      parseFloat(style.opacity) > 0 && // 元素不是透明的
      element.offsetWidth > 0 && // 元素有宽度
      element.offsetHeight > 0 // 元素有高度
    );

    // 输出详细的可见性检查结果
    console.log('%c元素可见性检查:', 'color: purple', {
      element: element.tagName + (element.id ? '#' + element.id : '') + (element.name ? '[name=' + element.name + ']' : ''),
      inIframe: isInIframe,
      offsetParent: element.offsetParent !== null,
      hasValidOffsetParent: hasValidOffsetParent,
      display: style.display,
      visibility: style.visibility,
      opacity: style.opacity,
      width: element.offsetWidth,
      height: element.offsetHeight,
      isVisible: isVisible
    });

    return isVisible;
  } catch (error) {
    console.error(`%c检查元素可见性时出错: ${error.message}`, 'color: red; font-weight: bold');
    // 如果出错，默认返回true，让程序尝试填写
    return true;
  }
}

// 为下拉选择框设置值
function setSelectValue(selectElement, value) {
  console.log('%c开始为下拉框设置值', 'color: blue; font-weight: bold');
  console.log('%c下拉框信息:', 'color: purple', {
    id: selectElement.id || '无',
    name: selectElement.name || '无',
    optionsCount: selectElement.options.length,
    currentValue: selectElement.value,
    currentText: selectElement.options[selectElement.selectedIndex]?.text || '无',
    targetValue: value
  });

  // 尝试找到包含指定值的选项
  let found = false;

  // 记录所有选项，用于调试
  const optionsText = [];
  console.log('%c下拉框所有选项:', 'color: purple');
  for (let i = 0; i < selectElement.options.length; i++) {
    const option = selectElement.options[i];
    optionsText.push(option.text);
    console.log(`选项 ${i}: value="${option.value}", text="${option.text}"`);

    if (option.text === value || option.value === value) {
      console.log(`%c找到精确匹配选项! 索引: ${i}, 值: ${option.value}, 文本: ${option.text}`, 'color: green; font-weight: bold');
      selectElement.value = option.value;
      found = true;
      break;
    }
  }

  // 如果没有找到精确匹配，尝试部分匹配
  if (!found) {
    console.log('%c未找到精确匹配选项，尝试部分匹配', 'color: orange; font-weight: bold');
    for (let i = 0; i < selectElement.options.length; i++) {
      const option = selectElement.options[i];
      if (option.text.includes(value) || value.includes(option.text)) {
        console.log(`%c找到部分匹配选项! 索引: ${i}, 值: ${option.value}, 文本: ${option.text}`, 'color: green; font-weight: bold');
        selectElement.value = option.value;
        found = true;
        break;
      }
    }
  }

  // 如果找到匹配项，触发change事件
  if (found) {
    console.log(`%c触发下拉框change事件，选中值: ${selectElement.value}`, 'color: blue');
    triggerChangeEvent(selectElement);
  } else {
    console.log(`%c未能设置下拉框值，可用选项: ${optionsText.join(', ')}`, 'color: red; font-weight: bold');
  }

  return found;
}

// 触发输入事件
function triggerInputEvent(element) {
  try {
    console.log(`%c触发输入事件，元素类型: ${element.tagName}, ID: ${element.id || '无ID'}, 名称: ${element.name || '无名称'}`, 'color: blue; font-weight: bold');
    console.log('%c元素信息:', 'color: purple', {
      tagName: element.tagName,
      id: element.id || '无',
      name: element.name || '无',
      type: element.type || '无',
      value: element.value || '无'
    });

    // 触发input事件
    console.log('%c触发input事件', 'color: orange');
    const inputEvent = new Event('input', { bubbles: true });
    const inputResult = element.dispatchEvent(inputEvent);
    console.log(`%cinput事件结果: ${inputResult ? '成功' : '被阻止'}`, inputResult ? 'color: green' : 'color: red');

    // 触发change事件
    console.log('%c触发change事件', 'color: orange');
    const changeEvent = new Event('change', { bubbles: true });
    const changeResult = element.dispatchEvent(changeEvent);
    console.log(`%cchange事件结果: ${changeResult ? '成功' : '被阻止'}`, changeResult ? 'color: green' : 'color: red');

    // 对于某些特殊的表单实现，可能需要额外的事件
    try {
      // 尝试触发blur事件
      console.log('%c触发blur事件', 'color: orange');
      const blurEvent = new Event('blur', { bubbles: true });
      const blurResult = element.dispatchEvent(blurEvent);
      console.log(`%cblur事件结果: ${blurResult ? '成功' : '被阻止'}`, blurResult ? 'color: green' : 'color: red');

      // 尝试触发keyup事件
      console.log('%c触发keyup事件', 'color: orange');
      const keyupEvent = new KeyboardEvent('keyup', { bubbles: true });
      const keyupResult = element.dispatchEvent(keyupEvent);
      console.log(`%ckeyup事件结果: ${keyupResult ? '成功' : '被阻止'}`, keyupResult ? 'color: green' : 'color: red');

      // 尝试触发更多可能的事件
      console.log('%c触发focusout事件', 'color: orange');
      element.dispatchEvent(new Event('focusout', { bubbles: true }));
    } catch (e) {
      console.log(`%c触发额外事件时出错: ${e.message}`, 'color: red; font-weight: bold');
    }

    return true;
  } catch (error) {
    console.error(`%c触发输入事件时出错: ${error.message}`, 'color: red; font-weight: bold');
    return false;
  }
}

// 触发change事件
function triggerChangeEvent(element) {
  try {
    console.log(`%c触发change事件，元素类型: ${element.tagName}, ID: ${element.id || '无ID'}, 名称: ${element.name || '无名称'}`, 'color: blue; font-weight: bold');
    console.log('%c元素信息:', 'color: purple', {
      tagName: element.tagName,
      id: element.id || '无',
      name: element.name || '无',
      type: element.type || '无',
      value: element.value || '无',
      selectedIndex: element.selectedIndex !== undefined ? element.selectedIndex : '不适用'
    });

    // 触发change事件
    console.log('%c触发change事件', 'color: orange');
    const changeEvent = new Event('change', { bubbles: true });
    const changeResult = element.dispatchEvent(changeEvent);
    console.log(`%cchange事件结果: ${changeResult ? '成功' : '被阻止'}`, changeResult ? 'color: green' : 'color: red');

    // 对于某些特殊的下拉框实现，可能需要额外的事件
    try {
      // 尝试触发click事件
      console.log('%c触发click事件', 'color: orange');
      const clickEvent = new MouseEvent('click', { bubbles: true });
      const clickResult = element.dispatchEvent(clickEvent);
      console.log(`%cclick事件结果: ${clickResult ? '成功' : '被阻止'}`, clickResult ? 'color: green' : 'color: red');

      // 尝试触发更多可能的事件
      console.log('%c触发input事件', 'color: orange');
      element.dispatchEvent(new Event('input', { bubbles: true }));
    } catch (e) {
      console.log(`%c触发额外事件时出错: ${e.message}`, 'color: red; font-weight: bold');
    }

    return true;
  } catch (error) {
    console.error(`%c触发change事件时出错: ${error.message}`, 'color: red; font-weight: bold');
    return false;
  }
}

// 显示通知
function showNotification(message) {
  // 创建通知元素
  const notification = document.createElement('div');
  notification.textContent = message;
  notification.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    background-color: #4285F4;
    color: white;
    padding: 10px 15px;
    border-radius: 4px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    z-index: 9999;
    font-family: 'Microsoft YaHei', Arial, sans-serif;
    font-size: 14px;
  `;

  // 添加到页面
  document.body.appendChild(notification);

  // 3秒后自动移除
  setTimeout(() => {
    notification.style.opacity = '0';
    notification.style.transition = 'opacity 0.5s';
    setTimeout(() => notification.remove(), 500);
  }, 3000);
}